/*
 * Copyright 2023, Haiku, Inc. All rights reserved.
 * Distributed under the terms of the MIT License.
 */

#include "WeatherView.h"

#include <Catalog.h>
#include <LayoutBuilder.h>
#include <GroupLayout.h>
#include <StringFormat.h>
#include <Window.h>
#include <Locale.h>

#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "WeatherView"

// 消息常量
const uint32 kMsgUpdateTime = 'updT';


WeatherView::WeatherView(const char* name)
	:
	BView(name, B_WILL_DRAW | B_PULSE_NEEDED),
	fWeatherIcon(NULL),
	fCurrentDateTime(BDateTime::CurrentDateTime(B_LOCAL_TIME))
{
	// 初始化界面
	_InitInterface();
	
	// 设置脉冲速率为1秒
	SetPulseRate(1000000);
}


WeatherView::~WeatherView()
{
	delete fWeatherIcon;
}


void
WeatherView::AttachedToWindow()
{
	BView::AttachedToWindow();
	
	// 更新时间和天气信息
	_UpdateDateTime();
	_UpdateWeather();
}


void
WeatherView::MessageReceived(BMessage* message)
{
	switch (message->what) {
		case kMsgUpdateTime:
			_UpdateDateTime();
			break;
		
		default:
			BView::MessageReceived(message);
			break;
	}
}


void
WeatherView::Pulse()
{
	// 每秒更新时间
	_UpdateDateTime();
}


void
WeatherView::_InitInterface()
{
	// 创建时间显示
	fTimeView = new BStringView("timeView", "");
	fTimeView->SetFont(be_bold_font);
	fTimeView->SetFontSize(24);
	
	// 创建日期显示
	fDateView = new BStringView("dateView", "");
	
	// 创建温度显示
	fTemperatureView = new BStringView("temperatureView", "");
	fTemperatureView->SetFont(be_bold_font);
	fTemperatureView->SetFontSize(18);
	
	// 创建天气状况显示
	fWeatherConditionView = new BStringView("weatherCondition", "");
	
	// 创建布局
	BGroupLayout* layout = new BGroupLayout(B_HORIZONTAL, 10);
	SetLayout(layout);
	
	// 添加控件到布局
	BLayoutBuilder::Group<>(layout)
		.AddGroup(B_VERTICAL, 5)
			.Add(fTimeView)
			.Add(fDateView)
		.End()
		.AddGlue()
		.AddGroup(B_VERTICAL, 5)
			.Add(fTemperatureView)
			.Add(fWeatherConditionView)
		.End()
		.SetInsets(10, 10, 10, 10);
}


void
WeatherView::_UpdateDateTime()
{
	// 更新当前时间
	fCurrentDateTime = BDateTime::CurrentDateTime(B_LOCAL_TIME);
	
	// 格式化时间显示
	BString timeString;
	timeString.SetToFormat("%02d:%02d:%02d", 
		fCurrentDateTime.Time().Hour(),
		fCurrentDateTime.Time().Minute(),
		fCurrentDateTime.Time().Second());
	fTimeView->SetText(timeString.String());
	
	// 格式化日期显示
	BString dateString;
	const char* weekdays[] = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
	int weekday = fCurrentDateTime.Date().DayOfWeek();
	
	dateString.SetToFormat("%d年%d月%d日 %s", 
		fCurrentDateTime.Date().Year(),
		fCurrentDateTime.Date().Month(),
		fCurrentDateTime.Date().Day(),
		weekdays[weekday]);
	fDateView->SetText(dateString.String());
}


void
WeatherView::_UpdateWeather()
{
	// 在实际应用中，这里应该从天气API获取数据
	// 这里仅作为示例，显示固定的天气信息
	
	// 设置温度
	fTemperatureView->SetText("25°C");
	
	// 设置天气状况
	fWeatherConditionView->SetText("晴朗");
}